/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.terminal_reason;

import moved.org.objectweb.asm.Label;
import moved.org.objectweb.asm.MethodVisitor;
import picounit.features.classloader.NullVisitor;

public class ReasonCapturingMethodVisitor extends NullVisitor implements MethodVisitor {
	private final ReasonRegistry reasonRegistry;

	private String className;
	private String name;

	private int line;
	private int evaluationLine;

	public ReasonCapturingMethodVisitor(ReasonRegistry reasonRegistry) {
		this.reasonRegistry = reasonRegistry;
	}

	public MethodVisitor visit(String className, String name) {
		this.className = className;
		this.name = name;
		this.evaluationLine = -1;

		return this;
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// MethodVisitor
	///////////////////////////////////////////////////////////////////////////////////////////////

	@Override
	public void visitLineNumber(int line, Label start) {
		this.line = line;
	}

	@Override
	public void visitMethodInsn(int opcode, String owner, String name, String desc) {
		if (desc.endsWith("Lpicounit/verify/ReasonCapturer;")) {
			evaluationLine = line;
		}
		else if (evaluationLine != -1 && owner.equals("picounit/verify/ReasonCapturer")) {
			reasonRegistry.registerReason(className, this.name, evaluationLine);

			evaluationLine = -1;
		}
	}
}
